﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using FANUC.DTO;
using Newtonsoft.Json;
using System.Web.Http.Description;

namespace FANUC.Controllers
{
    public class TodayAllRobotsRunningRatioController : ApiController
    {
        private FANUCDB db = new FANUCDB();

        [ResponseType(typeof(TodayAllRobotsRunningRatioDtoOutput))]
        public IHttpActionResult Get()
        {
            #region Test
            if (Helper.IsTest)
            {
                TodayAllRobotsRunningRatioDtoOutput testAllRatio = new TodayAllRobotsRunningRatioDtoOutput();
                testAllRatio.RunningRatio = 75.5M;
                testAllRatio.StopRatio = 20.1M;
                testAllRatio.Date = System.DateTime.Now.Date;
                return Ok(testAllRatio);
            }
            #endregion

            DateTime today0 = System.DateTime.Now.Date;
            DateTime now = System.DateTime.Now;

            var Robots = db.Robot.ToList();
            List<TodayRobotRunningRatioDtoOutput> ratioOfEachRobot = new List<TodayRobotRunningRatioDtoOutput>();
            foreach (var robot in Robots)
            {
                //此机器人当天第一个状态;-1:default,1:PowerOff,2:Fault,3:Ready,4:Running
                int firstState, lastState = -1;
                //第一次发生事件改变的时间点
                DateTime todayFirstChangeTime;
                //当前时间点

                var todayFirstChangeRecord = db.Robot_State_Change_History.Where(a => a.ChangeDateTime >= today0 && a.Robot_ID == robot.ID).OrderBy(a => a.ChangeDateTime).FirstOrDefault();
                if (todayFirstChangeRecord == null)
                {
                    todayFirstChangeTime = today0;
                    firstState = 1;
                }
                else
                {
                    todayFirstChangeTime = todayFirstChangeRecord.ChangeDateTime;
                    firstState = todayFirstChangeRecord.Changed_State_Type;
                }

                List<Robot_State_Change_History> allStateChangeRecords = db.Robot_State_Change_History.Where(a => a.ChangeDateTime > todayFirstChangeTime && a.Robot_ID == robot.ID).ToList();
                //按状态合计各状态时间(分钟)
                var stateGroupSumByState = from a in allStateChangeRecords group a by new { a.Original_State_Type } into grp select new { grp.Key.Original_State_Type, TotalMinutes = grp.Sum(a => a.Period) / 60 };

                //获取当天最后一个机器人状态
                var todayLastChangeRecord = db.Robot_State_Change_History.Where(a => a.ChangeDateTime > today0 && a.Robot_ID == robot.ID).OrderByDescending(a => a.ChangeDateTime).FirstOrDefault();
                DateTime lastChangeTime;
                if (todayLastChangeRecord == null)
                {
                    lastState = 1;
                    lastChangeTime = now;
                }
                else
                {
                    lastState = todayLastChangeRecord.Changed_State_Type;
                    lastChangeTime = todayLastChangeRecord.ChangeDateTime;
                }
                var todayTotalRunningSum = stateGroupSumByState.Where(a => a.Original_State_Type == 4).FirstOrDefault();
                int todayTotalRunningMinutes = Convert.ToInt16(todayTotalRunningSum == null ? 0 : todayTotalRunningSum.TotalMinutes) + (lastState == 4 ? Convert.ToInt16((now - lastChangeTime).TotalMinutes) : 0);
                int todayTotalMinutes = Convert.ToInt16((now - today0).TotalMinutes);
                decimal runningRatio = Convert.ToDecimal(todayTotalRunningMinutes) / todayTotalMinutes;
                TodayRobotRunningRatioDtoOutput ratio = new TodayRobotRunningRatioDtoOutput();
                ratio.RunningRatio = decimal.Round(runningRatio, 4);
                ratio.StopRatio = 1 - ratio.RunningRatio;
                ratio.Date = today0;
                ratio.RobotID = robot.ID.ToString();
                ratioOfEachRobot.Add(ratio);
            }
            decimal totalRunning = 0;
            foreach (var data in ratioOfEachRobot)
            {
                totalRunning += data.RunningRatio;
            }
            TodayAllRobotsRunningRatioDtoOutput allRatio = new TodayAllRobotsRunningRatioDtoOutput();
            allRatio.RunningRatio = decimal.Round(totalRunning * 100 / (100 * ratioOfEachRobot.Count()), 4);
            allRatio.StopRatio = 1 - allRatio.RunningRatio;
            allRatio.Date = today0;
            return Ok(allRatio);
        }

        public string Options()
        {
            return null;
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
